'use strict';
//服务订单列表
import React,{Component} from 'react';
import Header from '../../common/header';
import * as URLconstant from '../../constant/URLconstant'
import Util from '../../common/util';
import Modal from 'react-native-modalbox'
import Toast from '../../common/ToastUtil'
import MyVoucher from '../userVoucher/myVoucher';//订单服务券码
import Alipay from '../../common/Alipay';//支付
import OrderInfo from '../../order/orderInfo';//订单详情
import {
    View,
    Text,
    TouchableOpacity,
    Image,
    StyleSheet,
    ScrollView, ListView,
    Linking,
    Alert, DeviceEventEmitter
} from 'react-native';
export default class serviceOrderList extends Component{
    // 构造
      constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            orderName: [{ 'name': '待付款', 'status': 'pending' }, { 'name': '待使用', 'status': 'accepted' },
                { 'name': '服务中', 'status': 'shipped' }, { 'name': '已服务', 'status': 'finished' }],
            orderStatus:'pending',
            dataSource2: new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2}),
            dataSource: [],
            page:1,
            limit:10,
            isOver:false,
            loaded:true,
            again:true,
            phone_400:'',
            qq:[],
            isOpen:false
        };
        this.onEndReached=this.onEndReached.bind(this)
          this.renderFooter=this.renderFooter.bind(this)
          this._renderRow=this._renderRow.bind(this)
      }


    componentDidMount() {
        this.getOrderList()
        this.getContact()
        let that = this
        DeviceEventEmitter.addListener('orderList', function (Event) {
            // LOG("Event==========" + JSON.stringify(Event));
            let extras = Event.extras;
            let alertContent = Event.alertContent;
            if (extras == 9000) {
                that.getOrderlist()
            }

        });
    }

      async selectOrderStatus(status){
          await this.setState({
              orderStatus:status,
              dataSource2: new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2}),
              dataSource: [],
              page:1,
              limit:10,
              isOver:false,
              loaded:true,
              again:true
          })
          this.getOrderList()
      }



      getContact(){
          let url = URLconstant.GET_CONTACT
          let datakey=[]
          Util.get(url,datakey,this.getContactSuc.bind(this),this.errorCallback.bind(this))
      }

    getContactSuc(datas){
        if(qq.length!=0&&qq[0]!=''){
            this.setState({
                qq:datas.data.qq
            })
        }
        this.setState({
            phone_400:datas.data.phone_400,
        })
    }

      getOrderList(){
          let url = URLconstant.ORDERLIDT_URL
          let datakey=[]
          datakey['page'] = this.state.page;
          datakey['status'] = this.state.orderStatus;
          datakey['user_id'] = this.props.user_id;
          datakey['order_type'] = 1
          Util.get(url,datakey,this.getOrderListSuc.bind(this),this.errorCallback.bind(this))
      }

    getOrderListSuc(datas){
        if(datas.status==0){
            let isOver = false
            let again = true
            let total = datas.data.total
            let oldDatas = this.state.dataSource;
            let newList = datas.data.list
            if(newList.length<total.limit){
                isOver = true
                again = false
            }
            Array.prototype.push.apply(oldDatas, newList);
            this.setState({
                isOver:isOver,
                dataSource2: this.state.dataSource2.cloneWithRows(oldDatas),
                dataSource: oldDatas,
                loaded:false,
                page:this.state.page+1,
                again:again
            })
        }
    }
    errorCallback(err){

    }

    onEndReached(){
        let again = this.state.again
        if(again){
            this.getOrderList()
        }
    }
    renderFooter(){
        return (
            <View style={{height:30,alignItems:'center',justifyContent:'center'}}>
                <Text style={{fontSize:12,color:"#969696"}}>{this.state.isOver?"没有更多数据了":"正在加载中"}</Text>
            </View>
        )
    }

    toOrder(item){
          this.props.navigator.push({
              component: OrderInfo,
              passProps: {
                  order_id: item.order_id,
                  user_id: this.props.user_id
              }
          })
    }

    _renderRow(item){
        return(
            <View key={item.order_id} style={styles.order_item}>
                <View style={styles.order_header}>
                    <Text style={{fontSize:16,color:"#000",marginBottom:5}}>店铺:{item.seller_name}</Text>
                    <Text style={{fontSize:12,color:"#969696"}}>订单号:{item.order_sn}</Text>
                </View>
                <TouchableOpacity onPress={()=>this.toOrder(item)}>
                    {
                        item.order_goods.map((goods,index)=>{
                            return(
                                <View style={styles.goods_item} key={index}>
                                    <Image
                                        source={{uri:goods.goods_image}}
                                        resizeMode={'cover'}
                                        style={{width:85,height:85,}}
                                    />
                                    <View style={styles.goods_item_right}>
                                        <View>
                                            <Text style={{fontSize:15,color:"#333"}}>{goods.goods_name}</Text>
                                            <Text style={{fontSize:12,color:"#969696"}}>{goods.specification}</Text>
                                            <View style={styles.rows_view}>
                                                {
                                                    goods.quantity>goods.stock?
                                                        <Text style={{fontSize:12,color:"#f00",marginRight:10}}>(库存不足)</Text>:
                                                        null
                                                }
                                                {
                                                    goods.if_show==0?
                                                        <Text style={{fontSize:12,color:"#f00"}}>(已下架)</Text>:
                                                        null
                                                }
                                            </View>
                                        </View>
                                        <View style={styles.rows_view}>
                                            <Text style={{fontSize:14,color:"#333"}}>单价:</Text>
                                            <Text style={{fontSize:15,color:"#f00",marginLeft:5}}>¥{goods.price}</Text>
                                        </View>
                                    </View>
                                </View>
                            )
                        })
                    }
                </TouchableOpacity>
                <View style={styles.goods_total_wrap}>
                    <View style={[styles.rows_view,{marginBottom:5}]}>
                        <Text style={{fontSize:14,color:"#666"}}>共 {item.total} 件商品，合计</Text>
                        <Text style={{fontSize:14,color:"#f00"}}>¥{item.order_amount}</Text>
                    </View>
                    <View style={styles.rows_view}>
                        <Text style={{fontSize:12,color:"#aaa"}}>(含运费¥{item.shipping_fee}</Text>
                        {item.coupon_fee>0?<Text style={{fontSize:12,color:"#aaa"}}> -优惠券¥{item.coupon_fee}</Text>:null}
                        {item.surplus_money>0?<Text style={{fontSize:12,color:"#aaa"}}> -余额¥{item.surplus_money}</Text>:null}
                        {item.adjust_goods_fee>0?<Text style={{fontSize:12,color:"#aaa"}}> -后台调整价格¥{item.adjust_goods_fee}</Text>:null}
                        <Text style={{fontSize:12,color:"#aaa"}}>)</Text>
                    </View>
                </View>
                {this.backOrderBtn(item.order_id,item)}
            </View>
        )
    }

    toVoucher(order_id){
          this.props.navigator.push({
              component:MyVoucher,
              passProps:{
                  user_id:this.props.user_id,
                  order_id:order_id
              }
          })
    }


    toPay(item){
        let returnName = 'orderList'
        Alipay.alipayWithTradeNO(item.order_sn, item.seller_name, item.order_amount, returnName,item.alipaySign);
    }

    backOrderBtn(order_id,item){
          let orderStatus = this.state.orderStatus
        if(orderStatus=='pending'){
              return(
                  <View style={styles.goods_state}>
                      <TouchableOpacity style={styles.btn_style_1} onPress={()=>this.cancelOrder(order_id)}>
                          <Text style={{fontSize:14,color:"#333"}}>取消订单</Text>
                      </TouchableOpacity>
                      <TouchableOpacity style={styles.btn_style_2} onPress={()=>this.toPay(item)}>
                          <Text style={{fontSize:14,color:"#fff"}}>立即支付</Text>
                      </TouchableOpacity>
                  </View>
              )
        }else if(orderStatus=='accepted'||orderStatus=='shipped'){
              return(
                  <View style={styles.goods_state}>
                      <TouchableOpacity style={styles.btn_style_1} onPress={()=>this.setState({isOpen:true})}>
                          <Text style={{fontSize:14,color:"#333"}}>联系卖家</Text>
                      </TouchableOpacity>
                      <TouchableOpacity style={styles.btn_style_2} onPress={()=>this.toVoucher(order_id)}>
                          <Text style={{fontSize:14,color:"#fff"}}>查看券码</Text>
                      </TouchableOpacity>
                  </View>
              )
        }else{
            return(
                <View style={styles.goods_state}>
                    <TouchableOpacity style={styles.btn_style_1} onPress={()=>this.setState({isOpen:true})}>
                        <Text style={{fontSize:14,color:"#333"}}>联系卖家</Text>
                    </TouchableOpacity>
                </View>
            )
        }
    }

    cancelOrder(order_id){
          Alert.alert(
              '提示',
              "是否确定取消订单",
              [
                  {text:'取消',onPress:()=>LOG('press cancel')},
                  {text:'确定',onPress:()=>this.submitCancelOrder(order_id)}
              ]
          )
    }


    submitCancelOrder(order_id){
          let url = URLconstant.DELETEORDER_URL
        let datakey=[]
        datakey['order_id']=order_id
        datakey['user_id']=this.props.user_id
        Util.get(url,datakey,this.cancelOrderSuc.bind(this),this.errorCallback.bind(this))
    }

    async cancelOrderSuc(datas){
          Toast.show(datas.msg)
        if(datas.status==0){
            await this.setState({
                orderStatus:status,
                dataSource2: new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2}),
                dataSource: [],
                page:1,
                limit:10,
                isOver:false,
                loaded:true,
                again:true
            })
            this.getOrderList()
        }
    }

    callPhone(url){
          if(!url){
              Toast.show('联系方式不能为空，请联系后台管理员')
              return false
          }else{
              url='tel:'+url
              Linking.canOpenURL(url).then(supported => {
                  if (!supported) {
                      Toast.show('不支持拨打该联系方式')
                  } else {
                      return Linking.openURL(url);
                  }
              }).catch(err => Toast.show('错误的联系方式'));
          }
    }

    openQQ(qq){
          if(qq==''){
              Toast.show('联系QQ不能为空，请联系后台管理员')
              return false
          }
        Util.openQQ(qq)
    }


    showContactModal(){
          return(
              <Modal
                isOpen={this.state.isOpen}
                backdropPressToClose={false} swipeToClose={false}
                style={styles.contact_modal}
              >
                  <View style={styles.modal_header}>
                      <Text style={{fontSize:14,color:"#333"}}>联系卖家</Text>
                      <TouchableOpacity style={styles.close_btn} onPress={()=>this.setState({
                          isOpen:false
                      })}>
                          <Image
                              source={require('../../imgs/close.png')}
                              resizeMode={'cover'}
                              style={{width:20,height:20}}
                          />
                      </TouchableOpacity>
                  </View>
                  <View style={styles.contact_item}>
                      <View style={styles.contact_left}>
                          <Text style={{fontSize:12,color:"#333"}}>联系方式</Text>
                      </View>
                      <View style={styles.contact_center}>
                          <Text>{this.state.phone_400}</Text>
                      </View>
                      <TouchableOpacity onPress={()=>this.callPhone(this.state.phone_400)} style={styles.contact_right}>
                          <Text style={{fontSize:12,color:"#fff"}}>拨打电话</Text>
                      </TouchableOpacity>
                  </View>
                  {
                      this.state.qq.map((item,index)=>{
                          return(
                              <View key={index} style={styles.contact_item}>
                                  <View style={styles.contact_left}>
                                      <Text style={{fontSize:12,color:"#333"}}>联系QQ</Text>
                                  </View>
                                  <View style={styles.contact_center}>
                                      <Text>{item}</Text>
                                  </View>
                                  <TouchableOpacity onPress={()=>this.openQQ(item)} style={styles.contact_right}>
                                      <Text style={{fontSize:12,color:"#fff"}}>打开QQ</Text>
                                  </TouchableOpacity>
                              </View>
                          )
                      })
                  }
              </Modal>
          )
    }

      render(){
          return(
              <View style={{flex:1,backgroundColor:"#f0f0f0"}}>
                  <Header navigator={this.props.navigator} initObj={{ title: '服务订单',id:2}}/>
                  <View style={styles.header_view}>
                      {
                          this.state.orderName.map((item,index)=>{
                              return(
                                  <TouchableOpacity onPress={()=>this.selectOrderStatus(item.status)} style={styles.header_item} key={index}>
                                      <Text style={item.status==this.state.orderStatus?{fontSize:14,color:"#f00"}:{fontSize:14,color:"#696969"}}>{item.name}</Text>
                                  </TouchableOpacity>
                              )
                          })
                      }
                  </View>
                  {
                      this.state.loaded?
                          <View style={{flex:1,}}>
                              {Util.loading()}
                          </View>
                          :
                          <View style={{flex:1}}>
                              {
                                  this.state.dataSource.length==0?
                                      <View style={{flex:1,alignItems:'center',justifyContent:'center'}}>
                                          <Text>没有服务订单</Text>
                                      </View>
                                      :
                                      <ListView
                                          dataSource={this.state.dataSource2}
                                          onEndReached={this.onEndReached}
                                          renderRow={this._renderRow}
                                          renderFooter={this.renderFooter}
                                      />
                              }
                          </View>
                  }
                  {this.showContactModal()}
              </View>
          )
      }
}
var styles = StyleSheet.create({
    header_view:{
        backgroundColor:"#fff",
        flexDirection:'row',
        marginBottom:10
    },
    header_item:{
        flex:1,
        alignItems:'center',
        justifyContent:'center',
        height:45
    },
    order_item:{
        backgroundColor:"#fff",
        marginBottom:10,
        padding:5,
    },
    order_header:{
        borderBottomWidth:1,
        borderBottomColor:"#e0e0e0",
        paddingBottom:5
    },
    rows_view:{
        flexDirection:'row',
        alignItems:'center'
    },
    type_box:{
        borderWidth:1,
        borderColor:"#e7393c",
        alignItems:'center',
        justifyContent:'center',
        paddingHorizontal:5,
        height:20,
        borderRadius:5,
        marginLeft:5
    },
    goods_item:{
        paddingVertical:7,
        flexDirection:'row'
    },
    goods_item_right:{
        flex:1,
        justifyContent:'space-between',
        paddingLeft:10,
        height:85,
        flexWrap:'wrap'
    },
    goods_total_wrap:{
        alignItems:'flex-end',
        borderTopWidth:1,
        borderTopColor:"#e0e0e0",
        paddingVertical:7
    },
    goods_state:{
        alignItems:'center',
        borderTopWidth:1,
        borderTopColor:"#e0e0e0",
        height:40,
        justifyContent:'flex-end',
        flexDirection:'row'
    },
    opera_btn:{
        paddingHorizontal:10,
        height:26,
        borderRadius:5,
        alignItems:'center',
        justifyContent:'center',
        backgroundColor:"#e7393c",
    },
    code_modal:{
        width:300,
        height:380,
        alignItems:'center',
        justifyContent:'center'
    },
    modal_txt_view:{
        alignItems:'center',
        justifyContent:'center',
        width:200,
    },
    btn_style_1:{
        width:80,
        height:26,
        borderRadius:5,
        borderWidth:1,
        borderColor:"#d7d7d7",
        backgroundColor:"#fff",
        alignItems:'center',
        justifyContent:'center',
        marginLeft:10
    },
    btn_style_2:{
        width:80,
        height:26,
        borderRadius:5,
        borderWidth:1,
        borderColor:"#f65061",
        backgroundColor:"#f65061",
        alignItems:'center',
        justifyContent:'center',
        marginLeft:10
    },
    contact_modal:{
        width:300,
        height:300,
        borderRadius:5,
    },
    modal_header:{
        height:40,
        alignItems:'center',
        justifyContent:'center',
        borderBottomWidth:1,
        borderBottomColor:"#e0e0e0"
    },
    contact_item:{
        flexDirection:"row",
        height:50,
        alignItems:'center',
        paddingHorizontal:15,
    },
    contact_left:{
        width:70,
    },
    contact_center:{
        flex:1
    },
    contact_right:{
        width:60,
        height:20,
        alignItems:'center',
        justifyContent:'center',
        backgroundColor:"#f65061",
        borderRadius:4
    },
    close_btn:{
        position:'absolute',
        top:10,
        right:5,
    }
})